<template>
  <teleport to="body">
    <div class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4" v-if="visible">
      <div class="bg-white rounded-xl w-full max-w-5xl max-h-[90vh] overflow-y-auto">
        <div class="p-6 border-b border-gray-100 flex justify-between items-center">
          <h3 class="text-xl font-bold">{{ isEditMode ? '编辑产品' : '新增产品' }}</h3>
          <button class="text-gray-400 hover:text-gray-600" @click="$emit('close')">
            <i class="fa fa-times"></i>
          </button>
        </div>
        
        <div class="p-6 space-y-6">
          <!-- 基本信息 -->
          <div>
            <h4 class="text-lg font-medium mb-4">基本信息</h4>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">产品名称 <span class="text-danger">*</span></label>
                <input 
                  type="text" 
                  class="form-input" 
                  v-model="productForm.name"
                  placeholder="请输入产品名称"
                >
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">产品编号(SKU) <span class="text-danger">*</span></label>
                <input 
                  type="text" 
                  class="form-input" 
                  v-model="productForm.sku"
                  placeholder="请输入产品编号"
                  :readonly="isEditMode"
                >
                <p class="text-xs text-gray-500 mt-1" v-if="!isEditMode">系统自动生成，可修改</p>
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">所属站点 <span class="text-danger">*</span></label>
                <select class="form-input" v-model="productForm.siteId" @change="handleSiteChange">
                  <option value="">请选择站点</option>
                  <option v-for="site in sites" :key="site.id" :value="site.id">{{ site.name }}</option>
                </select>
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">所属分类 <span class="text-danger">*</span></label>
                <select class="form-input" v-model="productForm.categoryId">
                  <option value="">请选择分类</option>
                  <option 
                    v-for="category in productForm.siteId ? getSiteCategories(productForm.siteId) : []" 
                    :key="category.id" 
                    :value="category.id"
                  >
                    {{ getCategoryIndent(category.level) }}{{ category.name }}
                  </option>
                </select>
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">销售价(元) <span class="text-danger">*</span></label>
                <input 
                  type="number" 
                  step="0.01" 
                  min="0" 
                  class="form-input" 
                  v-model="productForm.price"
                  placeholder="请输入销售价"
                >
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">市场价(元)</label>
                <input 
                  type="number" 
                  step="0.01" 
                  min="0" 
                  class="form-input" 
                  v-model="productForm.originalPrice"
                  placeholder="请输入市场价"
                >
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">库存数量 <span class="text-danger">*</span></label>
                <input 
                  type="number" 
                  min="0" 
                  class="form-input" 
                  v-model="productForm.stock"
                  placeholder="请输入库存数量"
                >
              </div>
              
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-1">产品状态 <span class="text-danger">*</span></label>
                <select class="form-input" v-model="productForm.status">
                  <option value="draft">草稿</option>
                  <option value="online">已上线</option>
                  <option value="offline">已下线</option>
                </select>
              </div>
            </div>
          </div>
          
          <!-- 产品图片 -->
          <div>
            <div class="flex items-center justify-between mb-4">
              <h4 class="text-lg font-medium">产品图片</h4>
              <button 
                class="btn btn-secondary text-sm"
                @click="$emit('open-media-library')"
              >
                <i class="fa fa-image mr-1"></i>
                <span>从媒体库选择</span>
              </button>
            </div>
            
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">主图 <span class="text-danger">*</span></label>
              <div v-if="productForm.mainImage" class="relative mb-4">
                <img 
                  :src="productForm.mainImage" 
                  alt="产品主图" 
                  class="h-48 object-cover rounded border border-gray-200"
                >
                <button 
                  class="absolute top-2 right-2 w-8 h-8 bg-black bg-opacity-50 rounded-full flex items-center justify-center text-white hover:bg-opacity-70"
                  @click="removeMainImage"
                >
                  <i class="fa fa-times"></i>
                </button>
              </div>
              
              <div v-else class="mb-4">
                <div class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-lg">
                  <div class="space-y-1 text-center">
                    <i class="fa fa-cloud-upload text-gray-400 text-3xl"></i>
                    <div class="flex text-sm text-gray-600">
                      <label for="main-image-upload" class="relative cursor-pointer rounded-md bg-white text-primary focus-within:outline-none">
                        <span>上传主图</span>
                        <input id="main-image-upload" name="main-image-upload" type="file" class="sr-only" accept="image/*">
                      </label>
                      <p class="pl-1">或拖放文件</p>
                    </div>
                    <p class="text-xs text-gray-500">支持 PNG, JPG, GIF 格式，建议尺寸 800x800</p>
                  </div>
                </div>
              </div>
              
              <label class="block text-sm font-medium text-gray-700 mb-2">详情图</label>
              <div class="grid grid-cols-1 sm:grid-cols-3 md:grid-cols-4 gap-4 mb-4">
                <div 
                  v-for="(image, index) in productForm.images" 
                  :key="index"
                  class="relative group"
                >
                  <img 
                    :src="image" 
                    alt="产品图片" 
                    class="h-24 w-full object-cover rounded border border-gray-200"
                  >
                  <button 
                    class="absolute top-1 right-1 w-6 h-6 bg-black bg-opacity-0 group-hover:bg-opacity-50 rounded-full flex items-center justify-center text-white opacity-0 group-hover:opacity-100 transition-all"
                    @click="removeImage(index)"
                  >
                    <i class="fa fa-times text-xs"></i>
                  </button>
                  <button 
                    class="absolute bottom-1 right-1 w-6 h-6 bg-primary bg-opacity-0 group-hover:bg-opacity-80 rounded-full flex items-center justify-center text-white opacity-0 group-hover:opacity-100 transition-all"
                    @click="setAsMainImage(image)"
                    v-if="image !== productForm.mainImage"
                  >
                    <i class="fa fa-check text-xs"></i>
                  </button>
                </div>
                
                <div class="h-24 border-2 border-dashed border-gray-300 rounded flex items-center justify-center text-gray-400 hover:border-primary hover:text-primary cursor-pointer">
                  <i class="fa fa-plus"></i>
                </div>
              </div>
              
              <p class="text-xs text-gray-500">
                至少上传1张图片，最多上传8张，建议尺寸一致
              </p>
            </div>
          </div>
          
          <!-- 产品属性 -->
          <div>
            <div class="flex items-center justify-between mb-4">
              <h4 class="text-lg font-medium">产品属性</h4>
              <button 
                class="btn btn-secondary text-sm"
                @click="addAttribute"
              >
                <i class="fa fa-plus mr-1"></i>
                <span>添加属性</span>
              </button>
            </div>
            
            <div class="space-y-4">
              <div 
                v-for="(attr, index) in productForm.attributes" 
                :key="index"
                class="grid grid-cols-1 md:grid-cols-2 gap-4 items-end"
              >
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1">属性名称</label>
                  <input 
                    type="text" 
                    class="form-input" 
                    v-model="attr.name"
                    placeholder="例如：颜色、尺寸、材质等"
                  >
                </div>
                <div class="flex gap-2">
                  <div class="flex-1">
                    <label class="block text-sm font-medium text-gray-700 mb-1">属性值</label>
                    <input 
                      type="text" 
                      class="form-input" 
                      v-model="attr.value"
                      placeholder="多个值用逗号分隔，例如：红色,蓝色,绿色"
                    >
                  </div>
                  <button 
                    class="btn btn-danger h-10 px-3"
                    @click="removeAttribute(index)"
                    :disabled="productForm.attributes.length <= 1"
                  >
                    <i class="fa fa-trash"></i>
                  </button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 产品描述 -->
          <div>
            <h4 class="text-lg font-medium mb-4">产品描述</h4>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">简短描述</label>
              <textarea 
                class="form-input h-24" 
                v-model="productForm.description"
                placeholder="请输入产品简短描述，将显示在列表页"
              ></textarea>
            </div>
          </div>
          
          <!-- 产品详情 -->
          <div>
            <h4 class="text-lg font-medium mb-4">产品详情</h4>
            <!-- 简化的编辑器示例，实际项目中可集成专业编辑器 -->
            <div class="border border-gray-300 rounded-lg overflow-hidden">
              <div class="bg-gray-50 px-4 py-2 border-b border-gray-300 flex flex-wrap gap-2">
                <button class="p-1 hover:bg-gray-200 rounded" title="加粗"><i class="fa fa-bold"></i></button>
                <button class="p-1 hover:bg-gray-200 rounded" title="斜体"><i class="fa fa-italic"></i></button>
                <button class="p-1 hover:bg-gray-200 rounded" title="下划线"><i class="fa fa-underline"></i></button>
                <span class="h-4 border-r border-gray-300"></span>
                <button class="p-1 hover:bg-gray-200 rounded" title="左对齐"><i class="fa fa-align-left"></i></button>
                <button class="p-1 hover:bg-gray-200 rounded" title="居中对齐"><i class="fa fa-align-center"></i></button>
                <button class="p-1 hover:bg-gray-200 rounded" title="右对齐"><i class="fa fa-align-right"></i></button>
                <span class="h-4 border-r border-gray-300"></span>
                <button class="p-1 hover:bg-gray-200 rounded" title="插入图片" @click="$emit('open-media-library')"><i class="fa fa-image"></i></button>
                <button class="p-1 hover:bg-gray-200 rounded" title="插入链接"><i class="fa fa-link"></i></button>
                <button class="p-1 hover:bg-gray-200 rounded" title="插入表格"><i class="fa fa-table"></i></button>
              </div>
              <textarea 
                class="form-input border-0 rounded-none min-h-[400px]" 
                v-model="productForm.detailContent"
                placeholder="请输入产品详细内容..."
              ></textarea>
            </div>
          </div>
          
          <!-- 产品设置 -->
          <div>
            <h4 class="text-lg font-medium mb-4">产品设置</h4>
            <div class="flex flex-wrap gap-6">
              <label class="inline-flex items-center">
                <input 
                  type="checkbox" 
                  class="rounded border-gray-300 text-primary focus:ring-primary"
                  v-model="productForm.isNew"
                >
                <span class="ml-2 text-sm text-gray-700">标记为新品</span>
              </label>
              <label class="inline-flex items-center">
                <input 
                  type="checkbox" 
                  class="rounded border-gray-300 text-primary focus:ring-primary"
                  v-model="productForm.isHot"
                >
                <span class="ml-2 text-sm text-gray-700">标记为热销</span>
              </label>
              <label class="inline-flex items-center">
                <input 
                  type="checkbox" 
                  class="rounded border-gray-300 text-primary focus:ring-primary"
                  v-model="productForm.isRecommend"
                >
                <span class="ml-2 text-sm text-gray-700">推荐产品</span>
              </label>
            </div>
          </div>
        </div>
        
        <div class="p-6 border-t border-gray-100 flex justify-end gap-3">
          <button class="btn btn-secondary" @click="$emit('close')">
            <i class="fa fa-times"></i>
            <span>取消</span>
          </button>
          <button class="btn btn-primary" @click="handleSave">
            <i class="fa fa-check"></i>
            <span>{{ productForm.status === 'online' ? '保存并上线' : '保存' }}</span>
          </button>
        </div>
      </div>
    </div>
  </teleport>
</template>

<script setup>
import { defineProps, defineEmits, watch } from 'vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  isEditMode: {
    type: Boolean,
    default: false
  },
  currentId: {
    type: Number,
    default: null
  },
  sites: {
    type: Array,
    default: () => []
  },
  categories: {
    type: Array,
    default: () => []
  },
  productForm: {
    type: Object,
    default: () => ({
      name: '',
      sku: '',
      siteId: '',
      categoryId: '',
      mainImage: '',
      images: [],
      price: 0,
      originalPrice: 0,
      stock: 0,
      status: 'draft',
      isNew: false,
      isHot: false,
      isRecommend: false,
      attributes: [],
      description: '',
      detailContent: ''
    })
  }
})

const emit = defineEmits(['close', 'save', 'open-media-library'])

// 监听图片变化，如果主图为空且有详情图，则自动设置第一张为主要图片
watch(
  () => [props.productForm.images, props.productForm.mainImage],
  ([images, mainImage]) => {
    if (!mainImage && images.length > 0) {
      // 这里使用$emit或者直接修改props（在实际项目中应该通过emit更新父组件数据）
      console.log('自动设置第一张图片为主图')
    }
  },
  { deep: true }
)

// 处理站点变更
const handleSiteChange = () => {
  // 清空分类选择
  props.productForm.categoryId = ''
}

// 获取指定站点的分类
const getSiteCategories = (siteId) => {
  return props.categories.filter(cat => cat.siteId == siteId)
}

// 获取分类缩进
const getCategoryIndent = (level) => {
  return '　'.repeat(level) // 使用全角空格实现缩进
}

// 添加属性
const addAttribute = () => {
  props.productForm.attributes.push({ name: '', value: '' })
}

// 移除属性
const removeAttribute = (index) => {
  if (props.productForm.attributes.length <= 1) return
  props.productForm.attributes.splice(index, 1)
}

// 移除主图
const removeMainImage = () => {
  props.productForm.mainImage = ''
}

// 移除图片
const removeImage = (index) => {
  // 如果移除的是主图，也清空主图
  if (props.productForm.images[index] === props.productForm.mainImage) {
    props.productForm.mainImage = ''
  }
  props.productForm.images.splice(index, 1)
}

// 设置为主图
const setAsMainImage = (image) => {
  props.productForm.mainImage = image
}

// 处理保存
const handleSave = () => {
  // 简单验证
  if (!props.productForm.name) {
    alert('请输入产品名称')
    return
  }
  
  if (!props.productForm.sku) {
    alert('请输入产品编号')
    return
  }
  
  if (!props.productForm.siteId) {
    alert('请选择所属站点')
    return
  }
  
  if (!props.productForm.categoryId) {
    alert('请选择所属分类')
    return
  }
  
  if (props.productForm.price === null || props.productForm.price <= 0) {
    alert('请输入有效的销售价')
    return
  }
  
  if (props.productForm.stock === null || props.productForm.stock < 0) {
    alert('请输入有效的库存数量')
    return
  }
  
  if (!props.productForm.mainImage) {
    alert('请上传产品主图')
    return
  }
  
  // 提交保存
  emit('save')
}
</script>